package org.shijiagen.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.shijiagen.category.mapper.CategoryMapper;
import org.shijiagen.category.service.CategoryService;
import org.shijiagen.clients.ProductClient;
import org.shijiagen.param.PageParam;
import org.shijiagen.param.ProductHotParam;
import org.shijiagen.pojo.Category;
import org.shijiagen.utils.R;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;

    private final ProductClient productClient;

    @Override
    public Category byName(String categoryName) {
        return categoryMapper.selectOne(new QueryWrapper<Category>().eq("category_name",categoryName));
    }

    @Override
    public List<Integer> hotsCategory(ProductHotParam productHotParam) {
        List<Object> objects = categoryMapper.selectObjs(new QueryWrapper<Category>().in("category_name", productHotParam.getCategoryName())
                .select("category_id"));
        return objects.stream().map(obj->(Integer)obj).collect(Collectors.toList());
    }

    @Override
    public List<Category> list() {
        return categoryMapper.selectList(null);
    }

    @Override
    public R listPage(PageParam param) {
        Page<Category> categoryPage = categoryMapper.selectPage(new Page<Category>(param.getCurrentPage(), param.getPageSize()), null);
        return R.ok("类别分页数据查询成功",categoryPage.getRecords(),categoryPage.getTotal());
    }

    @Override
    public R save(Category category) {
        Long rows = categoryMapper.selectCount(new QueryWrapper<Category>().eq("category_name", category.getCategoryName()));
        if(rows > 0){
            return R.fail("类别已存在");
        }
        return categoryMapper.insert(category) > 0 ? R.ok("类别添加成功！") : R.fail("类别添加失败！");
    }

    @Override
    public R remove(Integer categoryId) {
        Long count = productClient.adminCount(categoryId);
        if (count != 0) return R.fail("类别下存在商品，删除失败！");
        return categoryMapper.deleteById(categoryId) > 0 ? R.ok("类别删除成功!") : R.fail("类别删除失败");
    }

    @Override
    public R update(Category category) {
        Long count = categoryMapper.selectCount(new QueryWrapper<Category>().eq("category_name", category.getCategoryName()));
        if(count > 0) return R.fail("类别名称已存在，不允许重复的类别名称");
        categoryMapper.updateById(category);
        return R.ok("类别名称修改成功");
    }
}
